package com.funny.stock.data.collect.impl;

import com.alibaba.fastjson.JSON;
import com.funny.stock.base.redis.RedisTool;
import com.funny.stock.base.util.PropertiesCopyUtil;
import com.funny.stock.data.collect.RealTimeStockService;
import com.funny.stock.data.collect.source.NetsStockDataSource;
import com.funny.stock.data.vo.RealtimeStockData;
import com.funny.stock.data.vo.SimpleRealtimeStockData;
import com.funny.stock.data.vo.Stock;
import com.funny.stock.data.vo.StockConstants;
import com.funny.stock.data.vo.StockStatus;
import com.funny.stock.data.vo.StockType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author pengl
 * @date 2020/11/9
 */
@Component
public class RealTimeStockServiceDelegate implements RealTimeStockService {

    @Autowired
    NetsStockDataSource dataSource;

    @Autowired
    RedisTool redisTool;

    @Override
    public StockStatus getStockStatus() {
        return dataSource.getStockStatus();
    }

    @Override
    public Map<String,RealtimeStockData> getStockDataList(List<Stock> stocks) {
        return dataSource.getStockDataList(stocks);
    }

    @Override
    public RealtimeStockData getRealtimeData(String code, StockType type) {
        String stockKey = StockConstants.KEY_STOCK_REALTIME_DATA_PREFIX + code ;
        String simpleStockKey = StockConstants.KEY_STOCK_REALTIME_SIMPLE_DATA_PREFIX ;
        String dataJson = (String) redisTool.get(stockKey);

        if(!StringUtils.isEmpty(dataJson)){
            return JSON.parseObject(dataJson,RealtimeStockData.class);
        }

        RealtimeStockData realtimeData = dataSource.getRealtimeData(code, type);
        if(realtimeData != null){
            redisTool.set(stockKey, JSON.toJSONString(realtimeData));
            redisTool.expire(stockKey, StockConstants.KEY_DEFAULT_EXPIRE_HOURS, TimeUnit.HOURS);
            SimpleRealtimeStockData simpleRealtimeStockData = PropertiesCopyUtil.copyProperties(realtimeData, SimpleRealtimeStockData.class);
            redisTool.hPut(simpleStockKey,simpleRealtimeStockData.getSymbol(),simpleRealtimeStockData);
            redisTool.expire(simpleStockKey, StockConstants.KEY_DEFAULT_EXPIRE_HOURS, TimeUnit.HOURS);
        }


        return realtimeData;
    }
}
